//
//  AZUserModel.swift
//  sinaWB
//
//  Created by AzeryKiss on 16/2/26.
//  Copyright © 2016年 AzeryKiss. All rights reserved.
//

import UIKit

class AZUserModel: NSObject, NSCoding {


    var access_token: String?
    // 千万不要给 var expires_in: NSTimeInterval?,基本数据类型必须给一个初始值,不给的话KVC找不这个属性

    var expires_in: NSTimeInterval = 0.0 {
        
        
        didSet{
            expires_data = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    
//    var remind_in: NSString?
    
    var uid: NSString?
    
    var expires_data: NSDate?
    
    
    
    
    var islogin: Bool = false
    
    func save(file: String) {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent(file)
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    
    class func decodeData(file: String) -> AZUserModel?{
        
        
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent(file)
        
        var userM = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? AZUserModel
            
            if let data = userM?.expires_data where data.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//                userM = nil
                return userM
            } else {
                userM = nil
                
        }
        


        return userM
    }
    
    
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_data, forKey: "expires_data")
        aCoder.encodeBool(islogin, forKey: "islogin")
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        self.expires_in = aDecoder.decodeObjectForKey("expires_in") as! NSTimeInterval
        self.uid = aDecoder.decodeObjectForKey("uid") as? String
        self.islogin = aDecoder.decodeBoolForKey("islogin")
        self.expires_data = aDecoder.decodeObjectForKey("expires_data") as? NSDate
    }
    
    
    // 字典转模型方法
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)

    }
    
    // 防止崩溃方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String)
    {}
    
}
